
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>重定向应用 &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="站点地图框架" href="sitemaps.html" />
    <link rel="prev" title="验证器" href="postgres/validators.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="postgres/validators.html" title="验证器">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="sitemaps.html" title="站点地图框架">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-contrib-redirects">
            
  <div class="section" id="s-module-django.contrib.redirects">
<span id="s-the-redirects-app"></span><span id="module-django.contrib.redirects"></span><span id="the-redirects-app"></span><h1>重定向应用<a class="headerlink" href="#module-django.contrib.redirects" title="永久链接至标题">¶</a></h1>
<p>Django 自带了一个可选的重定向应用程序。它可以让你在数据库中存储重定向，并为你处理重定向。它默认使用 HTTP 响应状态码 <code class="docutils literal notranslate"><span class="pre">301</span> <span class="pre">Moved</span> <span class="pre">Permanently</span></code>。</p>
<div class="section" id="s-installation">
<span id="installation"></span><h2>安装<a class="headerlink" href="#installation" title="永久链接至标题">¶</a></h2>
<p>要安装重定向应用程序，请按照这些步骤进行：</p>
<ol class="arabic simple">
<li>确保 <code class="docutils literal notranslate"><span class="pre">django.contrib.sites</span></code> 框架 <a class="reference internal" href="sites.html#enabling-the-sites-framework"><span class="std std-ref">已安装</span></a>。</li>
<li>将 <code class="docutils literal notranslate"><span class="pre">'django.contrib.redirects'</span></code> 添加到你的 <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 配置中。</li>
<li>在你的 <a class="reference internal" href="../settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> 配置中添加 <code class="docutils literal notranslate"><span class="pre">'django.contrib.redirects.middleware.RedirectFallbackMiddleware'</span></code>。</li>
<li>运行命令 <a class="reference internal" href="../django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code></a>。</li>
</ol>
</div>
<div class="section" id="s-how-it-works">
<span id="how-it-works"></span><h2>工作方式<a class="headerlink" href="#how-it-works" title="永久链接至标题">¶</a></h2>
<p><code class="docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code> 在数据库中创建一个 <code class="docutils literal notranslate"><span class="pre">django_redirect</span></code> 表。这是一个有 <code class="docutils literal notranslate"><span class="pre">site_id</span></code>、<code class="docutils literal notranslate"><span class="pre">old_path</span></code> 和 <code class="docutils literal notranslate"><span class="pre">new_path</span></code> 字段的查询表。</p>
<p><a class="reference internal" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware" title="django.contrib.redirects.middleware.RedirectFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectFallbackMiddleware</span></code></a> 完成了所有的工作。每当任何 Django 应用出现 404 错误时，这个中间件都会检查重定向数据库中请求的 URL，作为最后的手段。具体来说，它检查给定的 <code class="docutils literal notranslate"><span class="pre">old_path</span></code> 与站点 ID 对应的 <a class="reference internal" href="../settings.html#std:setting-SITE_ID"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SITE_ID</span></code></a> 设置的重定向。</p>
<ul class="simple">
<li>如果它找到了一个匹配的对象，并且 <code class="docutils literal notranslate"><span class="pre">new_path</span></code> 不是空的，它就会使用 301（“Moved Permanently”）重定向到 <code class="docutils literal notranslate"><span class="pre">new_path</span></code>。你可以将 <a class="reference internal" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware" title="django.contrib.redirects.middleware.RedirectFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectFallbackMiddleware</span></code></a> 子类化，并将 <a class="reference internal" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class" title="django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class"><code class="xref py py-attr docutils literal notranslate"><span class="pre">response_redirect_class</span></code></a> 设置为 <a class="reference internal" href="../request-response.html#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.http.HttpResponseRedirect</span></code></a> 以使用 <code class="docutils literal notranslate"><span class="pre">302</span> <span class="pre">Moved</span> <span class="pre">Temporary</span></code> 重定向。</li>
<li>如果它找到了一个匹配，并且 <code class="docutils literal notranslate"><span class="pre">new_path</span></code> 是空的，它就会发送一个 410（“Gone”）HTTP 头和空的（无内容）响应。</li>
<li>如果没有找到匹配的请求，则继续照常处理。</li>
</ul>
<p>中间件只有在 404 时才会被激活——而不是 500 或任何其他状态码的响应。</p>
<p>注意 <a class="reference internal" href="../settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> 的顺序很重要。一般来说，你可以把 <a class="reference internal" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware" title="django.contrib.redirects.middleware.RedirectFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectFallbackMiddleware</span></code></a> 放在列表的最后，因为这是最后的手段。</p>
<p>关于中间件的更多内容，请阅读 <a class="reference internal" href="../../topics/http/middleware.html"><span class="doc">中间件文档</span></a>。</p>
</div>
<div class="section" id="s-how-to-add-change-and-delete-redirects">
<span id="how-to-add-change-and-delete-redirects"></span><h2>如何添加、更改和删除重定向<a class="headerlink" href="#how-to-add-change-and-delete-redirects" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-via-the-admin-interface">
<span id="via-the-admin-interface"></span><h3>通过管理界面<a class="headerlink" href="#via-the-admin-interface" title="永久链接至标题">¶</a></h3>
<p>如果你已经激活了 Django 的自动管理界面，你应该会在管理索引页上看到“重定向”部分。像编辑系统中的其他对象一样编辑重定向。</p>
</div>
<div class="section" id="s-via-the-python-api">
<span id="via-the-python-api"></span><h3>通过 Python API<a class="headerlink" href="#via-the-python-api" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.contrib.redirects.models.Redirect">
<em class="property">class </em><code class="descclassname">models.</code><code class="descname">Redirect</code><a class="headerlink" href="#django.contrib.redirects.models.Redirect" title="永久链接至目标">¶</a></dt>
<dd><p>重定向由一个标准的 <a class="reference internal" href="../../topics/db/models.html"><span class="doc">Django 模型</span></a> 来表示，它位于 <a class="reference external" href="https://github.com/django/django/blob/main/django/contrib/redirects/models.py">django/contrib/redirects/models.py</a> 中。你可以通过 <a class="reference internal" href="../../topics/db/queries.html"><span class="doc">Django 数据库 API</span></a> 来访问重定向对象。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.redirects.models</span> <span class="kn">import</span> <span class="n">Redirect</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Add a new redirect.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">redirect</span> <span class="o">=</span> <span class="n">Redirect</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">site_id</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">old_path</span><span class="o">=</span><span class="s1">&#39;/contact-us/&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">new_path</span><span class="o">=</span><span class="s1">&#39;/contact/&#39;</span><span class="p">,</span>
<span class="gp">... </span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Change a redirect.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">redirect</span><span class="o">.</span><span class="n">new_path</span> <span class="o">=</span> <span class="s1">&#39;/contact-details/&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">redirect</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">redirect</span>
<span class="go">&lt;Redirect: /contact-us/ ---&gt; /contact-details/&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Delete a redirect.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Redirect</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">site_id</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">old_path</span><span class="o">=</span><span class="s1">&#39;/contact-us/&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go">(1, {&#39;redirects.Redirect&#39;: 1})</span>
</pre></div>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="s-middleware">
<span id="middleware"></span><h2>中间件<a class="headerlink" href="#middleware" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.contrib.redirects.middleware.RedirectFallbackMiddleware">
<em class="property">class </em><code class="descclassname">middleware.</code><code class="descname">RedirectFallbackMiddleware</code><a class="headerlink" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware" title="永久链接至目标">¶</a></dt>
<dd><p>你可以通过创建一个 <a class="reference internal" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware" title="django.contrib.redirects.middleware.RedirectFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectFallbackMiddleware</span></code></a> 的子类，并覆盖 <code class="docutils literal notranslate"><span class="pre">response_gone_class</span></code> 和／或 <code class="docutils literal notranslate"><span class="pre">response_redirect_class</span></code> 来改变中间件使用的 <a class="reference internal" href="../request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a> 类。</p>
<dl class="attribute">
<dt id="django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_gone_class">
<code class="descname">response_gone_class</code><a class="headerlink" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_gone_class" title="永久链接至目标">¶</a></dt>
<dd><p>当在请求的路径上没有找到 <a class="reference internal" href="#django.contrib.redirects.models.Redirect" title="django.contrib.redirects.models.Redirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Redirect</span></code></a> 或有一个空的 <code class="docutils literal notranslate"><span class="pre">new_path</span></code> 值时使用的 <a class="reference internal" href="../request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a> 类。</p>
<p>默认为 <a class="reference internal" href="../request-response.html#django.http.HttpResponseGone" title="django.http.HttpResponseGone"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseGone</span></code></a>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class">
<code class="descname">response_redirect_class</code><a class="headerlink" href="#django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class" title="永久链接至目标">¶</a></dt>
<dd><p>处理重定向的 <a class="reference internal" href="../request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a> 类。</p>
<p>默认为 <a class="reference internal" href="../request-response.html#django.http.HttpResponsePermanentRedirect" title="django.http.HttpResponsePermanentRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponsePermanentRedirect</span></code></a>。</p>
</dd></dl>

</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">重定向应用</a><ul>
<li><a class="reference internal" href="#installation">安装</a></li>
<li><a class="reference internal" href="#how-it-works">工作方式</a></li>
<li><a class="reference internal" href="#how-to-add-change-and-delete-redirects">如何添加、更改和删除重定向</a><ul>
<li><a class="reference internal" href="#via-the-admin-interface">通过管理界面</a></li>
<li><a class="reference internal" href="#via-the-python-api">通过 Python API</a></li>
</ul>
</li>
<li><a class="reference internal" href="#middleware">中间件</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="postgres/validators.html"
                        title="上一章">验证器</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="sitemaps.html"
                        title="下一章">站点地图框架</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/contrib/redirects.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="postgres/validators.html" title="验证器">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="sitemaps.html" title="站点地图框架">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>